﻿using System;
using System.Linq;
using LoD.Contracts;
using LoD.WPClientLibrary;
using LoD.WPClientLibrary.Animations;
using LoD.WPClientLibrary.Interfaces;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Animation = LoD.Contracts.Animation;


namespace LoD.WPClient.Modules {
    public class Playing : MapEngine, IGameModule {
        private readonly GameClass _game;
        private Sprite _character;
        private Direction _orientation;

        public Playing(GameClass game) : base(game) {
            this._game = game;
            this._orientation = Direction.Down;
            this.Random = new Random();
        }

        internal SpriteFont GuiFont { get; set; }
        internal Random Random { get; set; }

        #region IGameModule Members

        public new void Reset() { base.Reset(); }

        public new void LoadContent(ContentManager content) {
            base.LoadContent(content);
            this.GuiFont = content.Load<SpriteFont>("Fonts/Gui");

            this._character = new Sprite(content, this._game.SpriteBatch);
            this._character.Load("Creatures/SkeletonKnight");
            this._character.TotalFrames = 80;
            this._character.Columns = 9;
            this._character.Size = new Vector2(96, 96);
            this._character.Position = new Vector2(400, 240);
//            this._character.Animations.Add(new FrameLoop(0, 7, 1, 3) { ID = "1" });
        }

        public new void Update(TouchLocation touch, GameTime gameTime) {
            base.Update(touch, gameTime);

            if (touch.State == TouchLocationState.Pressed) {
                if (touch.Position.X < 270) {
                    if (touch.Position.Y < 160) this._orientation = Direction.UpLeft;
                    else if (touch.Position.Y < 320) this._orientation = Direction.Left;
                    else this._orientation = Direction.DownLeft;
                } else if (touch.Position.X > 530) {
                    if (touch.Position.Y < 160) this._orientation = Direction.UpRight;
                    else if (touch.Position.Y < 320) this._orientation = Direction.Right;
                    else this._orientation = Direction.DownRight;
                } else if (touch.Position.Y < 240) this._orientation = Direction.Up;
                else this._orientation = Direction.Down;

                foreach (var anim in this._character.Animations.Where(a => a.ID == "mobileAnimation"))
                    this._character.Animations.Remove(anim);
                this._character.Animations.Add(new FrameLoop(Animation.Stand, this._orientation));
            }
            this._character.Animate();
        }

        public void Draw(GameTime gameTime) {
            base.Draw(gameTime);
            this._character.Draw();
        }

        #endregion
    }
}